package com.demo.uploadpic_base64;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.util.ByteArrayBuffer;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

/**
 * 图片与Base64字符串的转换类
 * 
 * @author Mr.Y
 * 
 */
public class ImageToBase64 {

	/**
	 * 将图片转换成Base64字符串
	 * 
	 * @param imgPath
	 * @param bitmap
	 * @param imgFormat
	 * @return
	 */
	public static String imgToBase64(String imgPath, Bitmap bitmap) {

		ByteArrayBuffer out = null;
		try {

			File file = new File(imgPath);
			InputStream is = new FileInputStream(file);
			out = new ByteArrayBuffer(0);

			byte[] buffer = new byte[1024 * 1024 * 3];
			int len;
			while ((len = is.read(buffer)) != -1) {
				out.append(buffer, 0, len);
			}

			is.close();
			byte[] imgbytes = out.toByteArray();
			return Base64.encodeToString(imgbytes, Base64.NO_PADDING).trim();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			out = null;
		}

	}

	/**
	 * 
	 * @param base64Data
	 * @param imgName
	 * @param imgFormat
	 *            图片格式
	 */
	public static void base64ToBitmap(String base64Data, String imgName,
			String imgFormat) {
		byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
		Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

		File myCaptureFile = new File("/sdcard/", imgName);
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(myCaptureFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		boolean isTu = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
		if (isTu) {
			// fos.notifyAll();
			try {
				fos.flush();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
